import re
from flask import current_app
from flask import g
from flask import request
from flask import session

from ihome import constants
from ihome import db
from ihome.models import User
from ihome.utils.commons import login_required
from ihome.utils.image_storage import storage_image
from ihome.utils.response_code import RET
from . import api
from flask import jsonify


@api.route('/users')
@login_required
def users():
    """展示个人中心页面"""
    # 获取用户登录信息
    user_id = g.user_id
    
    # 通过用户id查询到这个用户
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")
    
    return jsonify(errno=RET.OK, errmsg="操作成功", data=user.to_dict())


@api.route('/user')
@login_required
def user():
    """展示个人中心页面"""
    # 获取用户登录信息
    user_id = g.user_id
    
    # 通过用户id查询到这个用户
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")
    
    data = {
        "name": user.name,
        "avatar": constants.QINIU_DOMIN_PREFIX + user.avatar_url
    }
    
    return jsonify(errno=RET.OK, errmsg="操作成功", data=data)


@api.route('/user/name', methods=["PUT"])
@login_required
def user_name():
    """修改用户名"""
    # 获取用户的登录信息
    user_id = g.user_id
    # 获取用户输入的用户名
    user_name = request.json.get("name")
    # 校验
    if not user_name:
        return jsonify(errno=RET.PARAMERR, errmsg="用户名不能为空")
    
    try:
        found_repetitive = User.query.filter(User.name == user_name).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    
    if found_repetitive:
        return jsonify(errno=RET.DATAEXIST, errmsg="昵称已存在")
    
    # ^[\u4E00-\u9FA5A-Za-z0-9]+$ 中文、英文、数字但不包括下划线等符号
    result = re.match("^[\u4E00-\u9FA5A-Za-z0-9]+$", user_name)
    if not result:
        return jsonify(errno=RET.PARAMERR, errmsg="昵称只能是中文、英文、数字")
    
    # 通过用户id修改用户的昵称
    try:

        user = User.query.get(user_id)
    
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在")
    
    try:
        user.name = user_name
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    
    return jsonify(errno=RET.OK, errmsg="OK")


@api.route('/user/avatar', methods=["POST"])
@login_required
def user_avatar():
    """上传头像"""
    # 获取用户的登录信息
    user_id = g.user_id
    
    # 获取用户的头像地址
    
    user_avatar_url = request.files.get("avatar")
    if not user_avatar_url:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    
    try:
        f = user_avatar_url.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR, errmsg="文件读写错误")


    try:
        avatar_url = storage_image(f)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="第三方系统错误")


    # 将地址保存到数据库
    try:
        user = User.query.get(user_id)
        if not user:
            return jsonify(errno=RET.USERERR,errmsg="用户不存在")
        user.avatar_url = avatar_url
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    
    return jsonify(errno=RET.OK, errmsg="保存成功", data=user.to_dict())


@api.route('/user/auth', methods=["POST","GET"])
@login_required
def user_auth():
    """房东实名验证"""
    # 获取用户登录信息
    user_id = g.user_id
    # 通过用户id查询用户
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询失败")
    
    if not user:
        return jsonify(errno=RET.USERERR,errmsg="该用户不存在")
        
    if request.method == "GET":
        return jsonify(errno=RET.OK,errmsg="OK",data=user.auth_to_dict())
        
    else:
        # 获取请求参数
        data_dict = request.json
        real_name = data_dict.get("real_name")
        id_card = data_dict.get("id_card")
        user_addr = data_dict.get("addr")
        
        # 校验参数
        if not all([real_name,id_card,user_addr]):
            return jsonify(errno=RET.PARAMERR,errmsg="参数错误")
        
        # 校验身份证号码,前17位必须是数字,第18位只能是数字或者Xx
        if len(id_card) != 18:
            return jsonify(errno=RET.PARAMERR, errmsg="身份证号码必须是18位")
        # 切片获取前17位身份证号码.
        seventeen_id = id_card[0:18]
        finally_id = id_card[-1]
        try:
            seventeen_id = int(seventeen_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg="身份证号码错误")
        
        if finally_id not in ["0","1","2","3","4","5","6","7","8","9","x"]:
            return jsonify(errno=RET.PARAMERR,errmsg="末位格式为小写x或数字")
        
        # 验证地区码
        area = {
            11: "北京",
            12: "天津",
            13: "河北",
            14: "山西",
            15: "内蒙古",
            21: "辽宁",
            22: "吉林",
            23: "黑龙江",
            31: "上海",
            32: "江苏",
            33: "浙江",
            34: "安徽",
            35: "福建",
            36: "江西",
            37: "山东",
            41: "河南",
            42: "湖北",
            43: "湖南",
            44: "广东",
            45: "广西",
            46: "海南",
            50: "重庆",
            51: "四川",
            52: "贵州",
            53: "云南",
            54: "西藏",
            61: "陕西",
            62: "甘肃",
            63: "青海",
            64: "宁夏",
            65: "新疆",
            71: "台湾",
            81: "香港",
            82: "澳门",
            91: "国外"
        }

        # 获取地区码
        area_id = int(id_card[0:2])
        try:
            # 用地区码作为键获取值,如果报错说明身份证号码错误
            addr = area[area_id]
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR,errmsg="身份证号地区非法")
        
        if addr != user_addr:
            return jsonify(errno=RET.PARAMERR,errmsg="身份证号地区非法")
        
        result = re.match("(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d[01][\dx]$)",id_card).group()
        
        if not result:
            return jsonify(errno=RET.PARAMERR,errmsg="身份证号码错误")
        
        # 验证真实姓名
        result = re.match("^[\u4e00-\u9fa5]{2,4}$",real_name).group()
        if not result:
            return jsonify(errno=RET.PARAMERR,errmsg="姓名错误")
        uu=User.query.filter(id_card == User.id_card).all()
        if uu:
            return jsonify(errno=RET.PARAMERR,errmsg="该身份证已被注册")

        try:
            user.real_name = real_name
            user.id_card = id_card
            user.addr = addr
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR,errmsg="数据库操作错误")
        
        
        return jsonify(errno=RET.OK,errmsg="OK",data=user.auth_to_dict())

@api.route("/user/pass_info",methods=['POST'])
@login_required
def pass_info():
    user_id=g.user_id
    data_dict=request.json
    old_password=data_dict.get('old_password')
    new_password=data_dict.get('new_password')
    new_password2=data_dict.get('new_password2')
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if  not all([old_password,new_password,new_password2]):
        return jsonify(errno=RET.DATAERR, errmsg='参数不完整')

    if new_password!=new_password2:
        return jsonify(errno=RET.PARAMERR, errmsg='参数有误')

    if not user.check_password(old_password):
        return jsonify(errno=RET.PARAMERR,errmsg="旧密码错误")

    user.password=new_password
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库操作失败')

    return jsonify(errno=RET.OK,errmsg='修改成功')